import gevent
import json
import os
from uuid import uuid4
from django.conf import settings
from pathlib import Path

from utils.yb_response import send_error, send_success
from utils.date import time_str


def handle_request(request, run_func):
    """
    处理请求
    :param request: 请求对象
    :param run_func: 执行方法
    :return:
    """
    if request.is_websocket():
        websocket = request.websocket
        # 当前操作索引
        try:
            while not websocket.is_closed():
                message = request.websocket.wait()
                if message:
                    receive_str = message.decode('utf8')
                    receive_dic: dict = json.loads(receive_str)
                    command = receive_dic.get('command')
                    print('<========', command)
                    print(receive_str)
                    g_run = gevent.spawn(run_func, receive_dic, websocket)
                    g_run.join()
                else:
                    websocket.close()
                    return send_success()
        except Exception as e:
            print('error = ', e)
            return

    else:
        return send_error('必须是 websocket 请求')


class MsgCommend:
    log = 1  # 正常日志
    err = 2  # 错误日志
    finish = 3  # 完成
    screenshot = 4  # 截图
    timeConsuming = 5
    use_case_err = 6 # 用例错误（用例错误是允许通过的）
    json = 7


def send_msg_with_date(websocket, msg, command=MsgCommend.log):
    """
    发送数据
    :param websocket:
    :param msg: 信息
    :param command: 命令
    :return:
    """
    send_data = {
        "date": time_str(),
        "msg": msg,
        "command": command
    }
    print(send_data)
    websocket.send(json.dumps(send_data))


def send_msg_screenshot(websocket):
    """
    截图, 并获取路径
    :param websocket:
    :return:
    """
    date_s = time_str('%Y-%m-%d')
    time_s = time_str('%H_%M')
    img_name = '%s.png' % uuid4()
    BASE_DIR = settings.BASE_DIR
    STATIC_URL = settings.STATIC_URL.replace('/', '')
    # 图片相对录几个文件夹
    img_relative_dir = os.path.join(STATIC_URL, 'screenshot', date_s, time_s)
    img_dir = os.path.join(BASE_DIR, img_relative_dir)
    img_dir_file = Path(img_dir)
    if not img_dir_file.is_dir():
        os.makedirs(img_dir)
    img_relative_path = os.path.join(img_relative_dir, img_name)
    img_path = os.path.join(BASE_DIR, img_relative_path)
    send_msg_with_date(websocket, img_relative_path, MsgCommend.screenshot)
    return img_path

